package com.haoyu.entity;

import com.haoyu.util.MyRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Scanner;

/**
 * @author: 蒿雨
 * @create: 2022-01-06 16:46
 * @description:
 */
public class AuthenticationTest {

    public static void main(String[] args) {
        testAuthentication();
    }

    public static void testAuthentication() {
        //实现自己的realm实例
        //MyRealm myRealm = new MyRealm();

        // 1.构建SecurityManager环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(new MyRealm());

        //2、主体提交认证请求
        // （1）设置SecurityManager环境
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        // （2）获取当前主体
        Subject subject = SecurityUtils.getSubject();

        //输入测试数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名");
        String userName = scanner.next();
        System.out.println("请输入密码");
        String pwd = scanner.next();
        System.out.println("请输入角色");
        String role = scanner.next();
        System.out.println("请输入权限");
        String permitted = scanner.next();

        UsernamePasswordToken token = new UsernamePasswordToken(userName, pwd);
        try {

            subject.login(token); //登录
        } catch (AuthenticationException e) {
            System.out.println("认证失败");
        }

        // subject.isAuthenticated()方法返回一个boolean值,用于判断用户是否认证成功
        System.out.println("认证结果:" + subject.isAuthenticated());
        // 判断subject是否具有admin和user两个角色权限,如没有则会报错
        //subject.checkRoles("admin");
        System.out.println("是否包含角色" + subject.hasRole(role));
        // 判断subject是否具有user:add权限
        //subject.checkPermission("user:add");
        System.out.println("是否包含权限" + subject.isPermitted(permitted));

    }


}
